package com.inews.business.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;
import com.inews.base.persistence.DynamicSpecifications;
import com.inews.base.persistence.SearchFilter;
import com.inews.base.persistence.SearchFilter.Operator;
import com.inews.base.utils.CollectionsUtil;
import com.inews.base.utils.MD5;
import com.inews.business.entity.Buyer;
import com.inews.business.repository.BuyerDao;

@Service 
@Transactional(readOnly = true)
public class BuyerServiceImpl implements BuyerService{
	
	@Autowired
	private BuyerDao buyerDao;
	
	
	
	/**
	 * 判断用户是否存在.
	 *
	 * @param username the username
	 * @return true, if exist buyer
	 */
	public Boolean existBuyer(String username){
		return buyerDao.exists(username);
	}
	
	
	
	/**
	 * 保存用户信息.
	 *
	 * @param buyer the buyer
	 */
	public void saveBuyer(Buyer buyer){
		buyer.setPassword(MD5.MD5Encode(buyer.getPassword()));
		buyerDao.save(buyer);
	}
	
	
	
	/**
	 * 校验用户信息.
	 *
	 * @param buyer the buyer
	 * @return the boolean
	 */
	public Boolean validUser(Buyer buyer){
		String username = buyer.getUsername();
		String password = buyer.getPassword();
		SearchFilter usernameFilter = new SearchFilter("username", Operator.EQ, username);
		SearchFilter passwordFilter = new SearchFilter("password", Operator.EQ, MD5.MD5Encode(password));
		List<Buyer> buyerList = buyerDao.findAll(DynamicSpecifications.bySearchFilter(Lists.newArrayList(usernameFilter, passwordFilter), Buyer.class));
		return (CollectionsUtil.isNotEmpty(buyerList) && buyerList.size() == 1);
	}
	
	
	
	/**
	 * 分页查询.
	 *
	 * @param pageable the pageable
	 * @return the page
	 */
	public Page<Buyer> findBuyerPage(Pageable pageable){
		return buyerDao.findAll(pageable);
	}
	
	
	
	public Buyer find(String username){
		return buyerDao.findOne(username);
	}
	
	
	
	public void update(Buyer buyer){
		buyerDao.save(buyer);
	}
	
	public void delete(String username){
		buyerDao.delete(username);
	}

}
